package com.da.javatest.interview.session2;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author chenlida
 * @date 2020/3/29 20:19
 *
 * 可重入锁测试
 */
public class Test09Lock {
    public static void main(String[] args) {
        Test09Lock test09Lock = new Test09Lock();

        // synchronized可重入性
        new Thread(() -> test09Lock.sendMsg(), "t1").start();
        new Thread(() -> test09Lock.sendMsg(), "t2").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // Lock可重入性
        new Thread(() -> test09Lock.get(), "t3").start();
        new Thread(() -> test09Lock.get(), "t4").start();
    }

    public synchronized void sendMsg() {
        System.out.println(Thread.currentThread().getName() + " " + "send message");
        sendEmail();
    }

    public synchronized void sendEmail() {
        System.out.println(Thread.currentThread().getName() + " " + "send email");
    }

    private Lock lock = new ReentrantLock();

    public void get() {
        lock.lock();
        // 加锁和解锁需要配对，不然会死锁
        // myLock.myLock();
        try {
            System.out.println(Thread.currentThread().getName() + " " + "get()");
            set();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void set() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + " " + "set()");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
